using UnityEngine;
using Delta2DGame.Base;

namespace Delta2DGame.State
{
    /// <summary>
    /// 敌人攻击状态
    /// </summary>
    public class AttackState : EnemyState
    {
        [SerializeField] private float attackRange = 1.5f;
        [SerializeField] private float attackCooldown = 1f;
        [SerializeField] private int attackDamage = 1;
        [SerializeField] private float chaseSpeed = 3f;
        [SerializeField] private float losePlayerRange = 5f;

        private float attackTimer = 0f;
        private Transform playerTransform;

        public AttackState(EnemyStateMachine stateMachine, EnemyController enemy, string animBoolName)
            : base(stateMachine, enemy, animBoolName)
        {}

        public override void Enter()
        {
            base.Enter();
            attackTimer = attackCooldown; // 允许立即攻击
            playerTransform = GameObject.FindGameObjectWithTag("Player")?.transform;
        }

        public override void Update()
        {
            base.Update();

            if (playerTransform == null)
            {
                // 找不到玩家，返回巡逻状态
                stateMachine.SwitchState(stateMachine.patrolState);
                return;
            }

            // 检测玩家是否超出追击范围
            float distanceToPlayer = Vector2.Distance(enemy.transform.position, playerTransform.position);
            if (distanceToPlayer > losePlayerRange)
            {
                stateMachine.SwitchState(stateMachine.returnState);
                return;
            }

            // 攻击冷却
            attackTimer += Time.deltaTime;
            if (attackTimer >= attackCooldown && distanceToPlayer <= attackRange)
            {
                Attack();
                attackTimer = 0f;
            }
        }

        public override void FixedUpdate()
        {
            base.FixedUpdate();

            if (playerTransform != null)
            {
                // 移动朝向玩家
                Vector2 direction = (playerTransform.position - enemy.transform.position).normalized;
                enemy.transform.position = Vector2.MoveTowards(
                    enemy.transform.position,
                    playerTransform.position,
                    chaseSpeed * Time.fixedDeltaTime
                );
            }
        }

        private void Attack()
        {
            // 触发攻击动画事件或直接应用伤害
            PlayerController player = playerTransform.GetComponent<PlayerController>();
            if (player != null)
            {
                // player.TakeDamage(attackDamage);
            }
            // 播放攻击动画
            animator.SetTrigger("Attack");
        }
    }
}